<template>
  <editor-layout class="edit" @ok="handleOk" v-on="$listeners" v-loading="loading" :loading="saveLoading">
    <el-form size="small" :model="model" :rules="rule" ref="form" @keyup.enter.native="handleOk()" label-width="110px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="报表名称" prop="reportName">
            <el-input v-model="model.reportName" placeholder="报表名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="enableFlag">
            <report-select v-model="model.enableFlag" type="ENABLE_FLAG" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="描述" prop="reportDesc">
            <el-input type="textarea" v-model="model.reportDesc"  />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="缩略图" prop="file">
            <file-upload ref="up1" :params="{xtlx: 'user-report'}" listType="picture"/>
            <file-view ref="fv1" :params="{xtlx: 'user-report', relateId: id}" v-if="id" type="picture"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </editor-layout>
</template>

<script>
import {postReportSave, getReportInfoId} from '@/api/report'
import {postFileUpdateRelate} from '@/api/file'
import fileUpload from '@/components/common/file/file-upload'
import fileView from '@/components/common/file/file-view'


export default {
  name: 'edit',
  components: {
    fileUpload,
    fileView
  },
  props: {
    id: [String, Number]
  },
  data() {
    return {
      loading: false,
      saveLoading: false,
      model: {
        reportName: '',
        enableFlag: 0,
        reportDesc: ''
      },
      rule: {
        reportName: [{required: true, message: '必填项'}]
      }
    }
  },
  methods: {
    async init() {
      if (this.id) {
        this.loadForm()
      }
    },
    async loadForm() {
      this.loading = true
      const data = await getReportInfoId(this.id).catch(e => {
        this.loading = false
        throw new Error(e)
      })
      this.model = data
      this.loading = false
    },
    handleOk() {
      this.$refs.form.validate(ok => {
        if(!ok) return

        const ids = []
        const images = this.$refs.up1.getData()
        images.forEach(o => ids.push(o.fileId))

        postReportSave(this.model).then(res => {
          const relateId = res.id
          const fileId = ids
          postFileUpdateRelate({relateId, fileId}).then(_ => {
            this.saveLoading = false
            this.$notify.success('保存成功！')
            this.$emit('on-ok')
          })
        })
      })
    }
  },
  mounted() {
    this.init()
  }
}
</script>


